// 引入七牛模块  
var qiniu = require("qiniu");
//要上传的空间名
var bucket = 'static';
var imageUrl = 'https://u.xiaowanwu.cn/'; // 域名名称
var accessKey = 's7PMp9cYjz0wmFG6tNn5yrmOxJZ1RDHP7cDB5e9A';
var secretKey = 'MbCcvb5pHrk7ZgymxehK1UUNR0Aho_I5XKFVAQcO';

const fs = require('fs');
const path = require('path');
const { uuid } = require("./utils");
var config;
var putPolicy;
var uploadToken;
exports.uploadFile = async function (ctx) {
  // 上传单个文件
  const file = ctx.request.files.file; // 获取上传文件

  console.log("ctx.request.files", ctx.request.files)
  // 创建可读流
  const reader = fs.createReadStream(file.path);
  // 构建图片名
  var fileName = uuid();
  // 构建图片路径
  var filePath = path.join(__dirname, '../tmp/' + fileName);
  // 创建可写流
  const upStream = fs.createWriteStream(filePath);
  // 可读流通过管道写入可写流

  let p = new Promise((resolve, reject) => {
    upStream.on('close', (fd) => { // 文件写入操作完成后触发
      console.log('文件关闭了', fd)
      var localFile = filePath;
      var formUploader = new qiniu.form_up.FormUploader(config);
      var putExtra = new qiniu.form_up.PutExtra();
      var key = fileName;
      // 文件上传
      formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr,
        respBody, respInfo) {
        console.log(respErr, respBody, respInfo)
        if (respErr) {
          reject(JSON.stringify(respBody));
          return;
        }
        if (respInfo.statusCode == 200) {
          var imageSrc = imageUrl + respBody.key;
          resolve(imageSrc);
        } else {
          reject(JSON.stringify(respBody));
        }
        // 上传之后删除本地文件
        fs.unlinkSync(filePath);
      });
    });
  });

  reader.pipe(upStream);
  return p;


}

function init() {
  var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

  var options = {
    scope: bucket,
  };
  putPolicy = new qiniu.rs.PutPolicy(options);
  uploadToken = putPolicy.uploadToken(mac);

  config = new qiniu.conf.Config();
  config.zone = qiniu.zone.Zone_z0;
}

setInterval(async () => {
  try {
    init();
  } catch (e) {
    console.log(e);
  }

}, 30 * 60 * 1000)
try {
  init();
} catch (e) {
  console.log(e);
}
